package com.sky.course.util;

import com.github.qcloudsms.SmsMultiSender;
import com.github.qcloudsms.SmsResultBase;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.httpclient.HTTPException;
import com.sky.course.entity.CmsMessageConfig;
import com.sky.course.entity.MessageForm;
import com.sky.course.entity.ValidatorUtils;
import com.sky.course.exception.CustomizeException;
import org.json.JSONException;

import java.io.IOException;

/**
* @Description:    发送短信工具类
* @Author:         Joe
* @CreateDate:     2019/10/28 22:04
*/
public class MessageUtils {

    /**
     * 按模板发送短信 支持单发和群发
     * @param isSingle 是否单发 true: 单发，false: 群发
     * @param form 需要发送的短信内容及收信人手机号
     * @param config 短信配置
     * @throws CustomizeException 发送失败时捕获的异常信息
     */
    public static void sendMessage(Boolean isSingle, MessageForm form, CmsMessageConfig config) throws CustomizeException {
        validateMessage(form, config);
        String regex = ";";
        //第一个参数是验证码，第二个是时间
        String[] params = {form.getCaptcha(),"3"};
        String[] phoneNumbers = form.getMobiles().split(regex);

        SmsResultBase result;
        try {
            // 是否单发
            if (isSingle) {
                SmsSingleSender ssender = new SmsSingleSender(config.getAppId(), config.getAppKey());
                result = ssender.sendWithParam("86", phoneNumbers[0], config.getTemplateId(), params, config.getSmsSign(), "", "");
            } else {
                SmsMultiSender msender = new SmsMultiSender(config.getAppId(), config.getAppKey());
                result =  msender.sendWithParam("86", phoneNumbers, config.getTemplateId(),params, config.getSmsSign(), "", "");
            }
            System.out.println("发完的结果"+result);
        } catch (HTTPException e) {
            e.printStackTrace();
            throw new CustomizeException("HTTP响应码错误");
        } catch (JSONException e) {
            e.printStackTrace();
            throw new CustomizeException("json解析错误");
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomizeException("网络IO错误");
        }
    }

    /**
     * 校验参数
     */
    private static void validateMessage(MessageForm messageForm, CmsMessageConfig messageConfig) throws CustomizeException {
        ValidatorUtils.validateEntity(messageForm);
        if (null == messageConfig) {
            throw new CustomizeException("系统参数异常");
        }
    }
}
